package execsedna;

import ru.ispras.sedna.driver.*;
import java.io.File;  
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.ArrayList;
import java.io.IOException;
import java.io.FileWriter;

public class ExecSedna {
	
	private static SednaConnection conection = null;
	
	private static final String QUERY_FILE = "DCSDQuery.txt";
	private static final String RESULTS_FILE = "Results.txt";
	
	private static SednaConnection getConection()
	{
		if ( conection == null )
		{
			try{
				conection = DatabaseManager.getConnection("localhost",  
	                    "GDSE",  
	                    "SYSTEM",  
	                    "MANAGER");			
			}
			catch(DriverException e) {  
		        e.printStackTrace();  
		    }  
		}
		
		return conection;
	}
	
	 /* Pretty printing for query results */  
	  private static void printQueryResults(SednaStatement st)  
	    throws DriverException {  
	    int count = 1;  
	    String item;  
	    SednaSerializedResult pr = st.getSerializedResult();  
	    while ((item = pr.next()) != null) {  
	      System.out.println(count + " item: " + item);  
	      count++;  
	    }  
	  }
	  
	  public static ArrayList<String> readQuery(){
		  	ArrayList<String> queries = new ArrayList<String>();
		  	
			File file = new File(QUERY_FILE);
			StringBuffer temp = new StringBuffer();    
			
			try {    
				FileReader arquivo = new FileReader(file);  
				BufferedReader ler = new BufferedReader(arquivo);  
				 
				boolean fim = false;  
				  
				while (!fim) {  
					String linha = ler.readLine();  
					if (linha == null)  
						fim = true;  
					else{
						if ( linha.isEmpty() ){
							if ( temp.length() > 0 )
							{
								queries.add(temp.toString());
								temp.delete(0, temp.length());
							}
							
							continue;
						}
						
						if ( linha.indexOf("#") > -1){
							temp.delete(0, temp.length());
						}
						else{
							temp.append(linha + " ");
						}
					}
				}  
				
				ler.close();  
				arquivo.close();  
			} catch (IOException erro) {  
				System.out.print("Erro :" + erro.toString());  
			} catch (SecurityException erro2) {  
				System.out.print("Erro :" + erro2.toString());  
			}
			return queries;
		}
	  
	  public static void writeResults(ArrayList<String> results){	
		//File file = new File(RESULTS_FILE);
		FileWriter fw;
		try {
			fw = new FileWriter(RESULTS_FILE, true);
			for ( int i = 0; i < results.size(); i++){
				fw.append(results.get(i));
			}
			
			fw.close();
		} catch (IOException erro) {  
			System.out.print("Erro :" + erro.toString());  
		} catch (SecurityException erro2) {  
			System.out.print("Erro :" + erro2.toString());  
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		ArrayList<String> queries = readQuery();
		// TODO Auto-generated method stub
		try{
		 /* Begin a new transaction */  
	      getConection().begin();  
	 
	      /* Create statement */  
	      SednaStatement st = getConection().createStatement();
	      ArrayList<String> results = new ArrayList<String>();
	      
	      for (int i = 0; i < queries.size(); i++)
	      {
			  long startTime = System.nanoTime();
			  boolean executou = st.execute(queries.get(i));
			  long stopTime = System.nanoTime();
			  long estimatedTime = stopTime - startTime;
			  String strResult =  "Consulta " + String.valueOf(i) + " Tempo: " + String.valueOf(estimatedTime*Math.pow(10, -9));
			  strResult += "\n";
			  results.add(strResult);
			  
			  System.out.println(strResult);			  
	      }
	      
	      writeResults(results);
	       
		}
		catch(DriverException e) {  
	        e.printStackTrace();  
	    } 

	}

}

